import { reqToCart ,reqCartList , reqCheckCart, reqDeleteCart } from "@/api";

const state = {
  cartList:[]
};
const mutations = {
  SET_CARTLIST(state,cartList){
    state.cartList = cartList
  }
};
const actions = {
  // 删除商品
  async deleteCart({commit},skuId){
    try {
      let result = await reqDeleteCart(skuId)
      if(result && result.code == 200){
        return 'ok'
      }
    } catch (error) {
      return Promise.reject(error)
    }
  },
  // 修改选中状态
  async setCheckCart({commit},{skuId,isChecked}){
    try {
      let result = await reqCheckCart(skuId,isChecked)
      if(result && result.code == 200){
        return 'ok'
      }
    } catch (error) {
      return Promise.reject(error)
    }
  },

  async getCartList({commit}){
    try {
      let result = await reqCartList()
      if(result && result.code == 200){
        commit('SET_CARTLIST',result.data)
      }
    } catch (error) {
      alert('获取购物车列表失败')
      return Promise.reject(error)
    }
  },



  // 自己用路由发的请求
  async setAddCart({ commit }, { skuId, skuNum }) {
    try {
      let result = await reqToCart(skuId, skuNum);
      console.log(result);
      if (result && result.code == 200) {
        return 'ok'
      }
      return Promise.reject('参数错误',result.data)
    } catch (error) {
        return Promise.reject(error)
    }
  },
};
const getters = {};
export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters,
};
